import 'package:flutter/material.dart';
import '../config/config.dart';
import '../utils/HttpRequest.dart';

/// 仓库搜索页面组件
class RepositorySearchPage extends StatefulWidget {
  /// 创建RepositorySearchPage实例
  const RepositorySearchPage({super.key});

  @override
  /// 创建页面状态管理对象
  State<RepositorySearchPage> createState() => _RepositorySearchPageState();
}

/// RepositorySearchPage的状态管理类
class _RepositorySearchPageState extends State<RepositorySearchPage> {
  /// 构造函数，初始化默认的token值
  _RepositorySearchPageState() {
    _tokenController.text = AppConfig.demoToken;
  }

  /// 输入框控制器：存储搜索关键字
  final _keywordController = TextEditingController();
  
  /// 输入框控制器：存储用户的Access Token
  final _tokenController = TextEditingController();
  
  /// 表单验证的全局键
  final _formKey = GlobalKey<FormState>();
  
  /// GitCode API客户端实例，用于发送网络请求
  final _client = GitCodeApiClient();

  /// 仓库搜索结果列表
  List<GitCodeRepository> _repoResults = const [];
  
  /// 错误信息，用于展示API调用失败时的提示
  String? _errorMessage;
  
  /// 加载状态标志，控制加载指示器的显示
  bool _isLoading = false;
  
  /// 控制token输入框是否显示为密码形式
  bool _obscureToken = true;

  @override
  /// 释放资源，清理控制器
  void dispose() {
    _keywordController.dispose();
    _tokenController.dispose();
    super.dispose();
  }

  /// 执行仓库搜索
  Future<void> _performSearch() async {
    // 防止重复提交
    if (_isLoading) return;
    
    // 验证表单
    if (!_formKey.currentState!.validate()) return;

    // 收起键盘
    FocusScope.of(context).unfocus();

    // 重置状态，显示加载指示器
    setState(() {
      _isLoading = true;
      _errorMessage = null;
      _repoResults = const [];
    });

    // 获取token值
    final token = _tokenController.text.trim();

    try {
      // 执行仓库搜索API请求
      final repos = await _client.searchRepositories(
        keyword: _keywordController.text,
        personalToken: token,
        perPage: 8,
      );
      setState(() {
        _repoResults = repos;
      });
    } on GitCodeApiException catch (error) {
      // 处理特定的API异常
      setState(() {
        _errorMessage = error.message;
      });
    } catch (error) {
      // 处理其他未预期的异常
      setState(() {
        _errorMessage = '未知错误：$error';
      });
    } finally {
      // 确保在组件仍挂载时更新状态
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  /// 构建页面UI布局
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('仓库搜索'),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildIntro(),
              const SizedBox(height: 20),
              _buildFormCard(),
              const SizedBox(height: 20),
              _buildResultSection(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建页面介绍文本组件
  Widget _buildIntro() {
    return const Text(
      '输入关键字 + access token，立即查询 GitCode 仓库（搜索接口需授权）。',
      style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
    );
  }

  /// 构建搜索表单卡片
  Widget _buildFormCard() {
    return Card(
      elevation: 0,
      clipBehavior: Clip.antiAlias,
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              TextFormField(
                controller: _keywordController,
                textInputAction: TextInputAction.search,
                decoration: const InputDecoration(
                  labelText: '搜索关键字',
                  hintText: '例如：spark',
                  prefixIcon: Icon(Icons.search),
                ),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '请输入关键字';
                  }
                  return null;
                },
                onFieldSubmitted: (_) => _performSearch(),
              ),
              const SizedBox(height: 12),
              TextFormField(
                controller: _tokenController,
                decoration: InputDecoration(
                  labelText: 'Access Token',
                  hintText: 'GitCode 个人设置 > Access Token',
                  prefixIcon: const Icon(Icons.vpn_key_outlined),
                  suffixIcon: IconButton(
                    icon: Icon(
                      _obscureToken
                          ? Icons.visibility_off_outlined
                          : Icons.visibility_outlined,
                    ),
                    onPressed: () {
                      setState(() {
                        _obscureToken = !_obscureToken;
                      });
                    },
                  ),
                ),
                obscureText: _obscureToken,
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '搜索接口需提供 access token';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              FilledButton.icon(
                onPressed: _isLoading ? null : _performSearch,
                icon: _isLoading
                    ? const SizedBox(
                        width: 18,
                        height: 18,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Icon(Icons.play_arrow_rounded),
                label: Text(_isLoading ? '查询中...' : '查询'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建结果展示区域
  Widget _buildResultSection() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      // 显示错误信息
      return _InfoBanner(
        icon: Icons.error_outline,
        background: Colors.red.withOpacity(0.08),
        textColor: Colors.red.shade700,
        message: _errorMessage!,
      );
    }

    return _buildRepositoryResults();
  }

  /// 构建仓库搜索结果列表
  Widget _buildRepositoryResults() {
    if (_repoResults.isEmpty) {
      return const _InfoBanner(
        icon: Icons.info_outline,
        background: Color(0xFFEFF4FF),
        textColor: Color(0xFF1A237E),
        message: '还没有结果，输入关键字并点击查询即可获取仓库列表。',
      );
    }

    return Column(
      children: _repoResults.map(_RepoTile.new).toList(),
    );
  }
}

/// 信息横幅组件
class _InfoBanner extends StatelessWidget {
  /// 创建信息横幅组件
  const _InfoBanner({
    required this.icon,
    required this.background,
    required this.textColor,
    required this.message,
  });

  /// 显示的图标
  final IconData icon;
  
  /// 背景颜色
  final Color background;
  
  /// 文字颜色
  final Color textColor;
  
  /// 要显示的消息内容
  final String message;

  @override
  /// 构建信息横幅UI
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: background,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, color: textColor),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              message,
              style: Theme.of(context)
                  .textTheme
                  .bodyMedium
                  ?.copyWith(color: textColor),
            ),
          ),
        ],
      ),
    );
  }
}

/// 仓库信息卡片组件
class _RepoTile extends StatelessWidget {
  /// 创建仓库信息卡片
  const _RepoTile(this.repo);

  /// 仓库搜索结果数据
  final GitCodeRepository repo;

  @override
  /// 构建仓库信息卡片UI
  Widget build(BuildContext context) {
    return Card(
      elevation: 0,
      margin: const EdgeInsets.only(bottom: 12),
      child: ListTile(
        leading: const Icon(Icons.folder_outlined),
        title: Text(repo.fullName, style: const TextStyle(fontWeight: FontWeight.w600)),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (repo.description?.isNotEmpty == true)
              Padding(
                padding: const EdgeInsets.only(bottom: 4),
                child: Text(
                  repo.description!,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            Wrap(
              spacing: 8,
              runSpacing: 4,
              children: [
                // 语言、Star、Fork 三种常见指标，Chip 形式展示。
                if (repo.language != null)
                  _StatChip(label: '语言', valueLabel: repo.language),
                _StatChip(label: 'Star', value: repo.stars),
                _StatChip(label: 'Fork', value: repo.forks),
              ],
            ),
            const SizedBox(height: 4),
            Text(
              '更新 ${repo.updatedAt ?? '-'}',
              style: const TextStyle(fontSize: 12),
            ),
            Text(
              repo.webUrl,
              style: const TextStyle(fontSize: 12, color: Colors.blue),
            ),
          ],
        ),
      ),
    );
  }
}

/// 统计信息标签组件
class _StatChip extends StatelessWidget {
  /// 创建统计信息标签
  const _StatChip({
    required this.label,
    this.value,
    this.valueLabel,
  });

  /// 标签文本，如"Star"、"Fork"、"语言"等
  final String label;
  
  /// 要显示的数值，当valueLabel为null时使用
  final int? value;
  
  /// 要显示的文本值，优先级高于value属性
  final String? valueLabel;

  @override
  /// 构建统计信息标签UI
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;
    // 优先使用valueLabel，如果为null则使用value，如value也为null则显示0
    final display = valueLabel ?? (value ?? 0).toString();
    
    return Chip(
      label: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            display,
            style: textTheme.titleMedium,
          ),
          Text(label, style: textTheme.bodySmall),
        ],
      ),
    );
  }
}